<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>学生信息管理</span>
      </div>
    </template>
    <el-form :model="studentModel" :rules="rules" label-width="100px">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input v-model="studentModel.studentName"></el-input>
      </el-form-item>
      <el-form-item label="班级码" prop="clazzId">
        <el-input v-model="studentModel.clazzId"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="studentModel.sex" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateStudent">确认</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { fetchStudentInfo, updateStudentInfo } from '@/api/studentService.js';
import { useTokenStore } from '@/stores/token.js'; // 引入 useTokenStore

const tokenStore = useTokenStore(); // 获取 tokenStore 实例

const studentModel = ref({
  id: null,
  studentName: '',
  clazzId: null,
  sex: ''
});

const rules = {
  studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
  clazzId: [{ required: true, message: '请输入班级码', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
};

const fetchStudent = async () => {
  try {
    const result = await fetchStudentInfo(tokenStore.token); // 传递 token
    if (result.code === 0 && result.data) {
      studentModel.value = result.data;
    } else {
      ElMessage.error('未能正确获取学生信息');
    }
  } catch (error) {
    if (error.message.includes('Unauthorized')) {
      ElMessage.error('未授权访问，请重新登录');
    } else {
      ElMessage.error('请完善信息');
    }
  }
};

const updateStudent = async () => {
  try {
    const result = await updateStudentInfo(studentModel.value, tokenStore.token); // 传递 token
    if (result.code === 0) {
      ElMessage.success(result.msg || '修改成功');
    } else {
      ElMessage.error(result.msg || '修改失败');
    }
  } catch (error) {
    if (error.message.includes('Unauthorized')) {
      ElMessage.error('未授权访问，请重新登录');
    } else {
      ElMessage.error('修改学生信息失败');
    }
  }
};

onMounted(() => {
  fetchStudent();
});
</script>


<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
